/**
 * vue中使用的插件，主要功能有loading和弹窗
 * 1、在main.js全局导入这个js文件
 *    import {util} from "./assets/js/util";
 *     Vue.prototype.util = util;
 * 2、例：调用showLoading()这个方法
 *    this.util.showLoading()
 * 
 * 
 *  
 * 
 * */ 
const util = {
  //提示弹窗 全局调用：this.util.showAlertPublic("");单文件调用：import {util} from "./util";util.showAlertPublic("")
  showAlertPublic(content) {
      let objE = document.createElement("div");
      let newAlertItem = "<div style='position: fixed;z-index: 10;top: 0;left: 0;bottom: 0;right: 0;margin: auto;width: 100%;height: 100%;z-index: 2019;'><div style='position: absolute;top: 50%;left: 50%;width: 40%;height: 1.04rem;margin-top: -.92rem;margin-left: -20%;padding: 0.08rem 0.16rem;background: #434444;font-size: 0.24rem;border-radius: 6px;color: white;display: -webkit-box;display: -ms-flexbox;display: flex;-ms-flex-wrap: wrap;flex-wrap: wrap;-webkit-box-pack: center;-ms-flex-pack: center;justify-content: center;-webkit-box-align: center;-ms-flex-align: center;align-items: center;'>" + content + "</div></div>";
      objE.innerHTML = newAlertItem;
      document.body.appendChild(objE);
      setTimeout(() => {
          document.body.removeChild(objE);
      }, 1000)
  },
  //loading加载 全局调用：this.util.showLoading("");单文件调用：import {util} from "./util";util.showLoading("")
  showLoading() {
      let objE = document.createElement("div");
      objE.setAttribute("id", "utilLoading");
      let newAlertItem = "<div style='position: fixed;z-index: 10;top: 0;left: 0;bottom: 0;right: 0;margin: auto;width: 100%;height: 100%;z-index: 2019;display: -webkit-box;display: -ms-flexbox;display: flex;-ms-flex-wrap: wrap;flex-wrap: wrap;-webkit-box-pack: center;-ms-flex-pack: center;justify-content: center;-webkit-box-align: center;-ms-flex-align: center;align-items: center;'><div style='background:url() no-repeat;width: 32px;height: 32px;'></div></div>";
      objE.innerHTML = newAlertItem;
      document.body.appendChild(objE);
  },
  //隐藏loading加载 全局调用：this.util.hideLoading("");单文件调用：import {util} from "./util";util.hideLoading("")
  hideLoading() {
      document.body.removeChild(document.getElementById("utilLoading"));
  },
  //name为参数名，queryString为链接
  getQueryString(name, queryString) {
      name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
      if (!queryString) {
          queryString = location.search ? location.search : location.hash;
      }
      let regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
          results = regex.exec(queryString);
      return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  },
  // 删除url中某个参数,并跳转
  UrlQueryDel(name) {
      let loca = window.location;
      let baseUrl = loca.origin + loca.pathname + "?";
      let query = loca.search.substr(1);
      if (query.indexOf(name) > -1) {
          let obj = {}
          let arr = query.split("&");
          for (let i = 0; i < arr.length; i++) {
              arr[i] = arr[i].split("=");
              obj[arr[i][0]] = arr[i][1];
          };
          delete obj[name];
          let url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g, "").replace(/\:/g, "=").replace(/\,/g, "&");
          return url
      }else{
          return location.href
      }
  },
  UrlQueryAdd(url,name,value){
      console.log(url)
      if (url.indexOf('?') != -1){
          return url + "&" + name + "=" + value;
      }else{
          return url + "?" + name + "=" + value;
      }
  },
  //跳转判断
  checkLoginAndTo(that, url) {
      //判断是否登录
      //{"user_id":3568000,"token":"beca89bf92114cfbfc5bef9b3772e18c4d29f657","secret_key":"142d5c038984060ddaff6668fca672c1"}
      //cookie 名称 auth
      if (!this.getCookie("auth")) {
          that.$router.push("/login" + location.search)
          return false
      }
      that.$router.push(url)
  },
  //登录判断
  checkLogin() {
      if (!this.getCookie("auth")) {
          return false
      } else {
          return true
      }
  },
  //微信环境判断
  isWeiXin() {
      let ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == 'micromessenger' || ua.match(/_SQ_/i) == '_sq_') {
          return true;
      } else {
          return false;
      }
  },
  //设置cookie  
  //name是cookie中的名，value是对应的值，iTime是多久过期（单位为天）  
  setCookie(name, value, iTime) {
      let oDate = new Date();
      let val = escape(JSON.stringify(value));
      let domain = "." + location.host.split(".")[1] + "." + location.host.split(".")[2];
      //设置cookie过期时间  
      oDate.setDate(oDate.getDate() + iTime);
      //加个判断是本地服务器还是域名服务器
      if (location.host.split(".").length > 3) {
          document.cookie = name + '=' + val + ';expires=' + oDate.toGMTString();
      } else {
          document.cookie = name + '=' + val + ';expires=' + oDate.toGMTString() + ";path=/;domain=" + domain;
      }
  },
  //获取cookie  
  getCookie(name) {
      //cookie中的数据都是以分号加空格区分开  
      let arr = document.cookie.split("; ");
      for (let i = 0; i < arr.length; i++) {
          if (arr[i].split("=")[0] == name) {
              return unescape(arr[i].split("=")[1]);
          }
      }
      //未找到对应的cookie则返回空字符串  
      return '';
  },
  //删除cookie  
  removeCookie(name) {
      //调用setCookie方法，把时间设置为-1  
      this.setCookie(name, 1, -1);
  },
  // 处理时间数据格式函数
  disposeData(obj) {
      let typeObj = Object.prototype.toString.call(obj) == "[object Object]"
      let typeAry = Object.prototype.toString.call(obj) == "[object Array]"
      if (typeObj) {
          Object.keys(obj).forEach((i) => {
              if (i == 'begin_date') {
                  obj[i] = setStr(obj[i])
              }
              if (i == 'end_date') {
                  obj[i] = setStr(obj[i])
              }
              if (i == "activity_end_date") {
                  obj[i] = setStr(obj[i])
              }
              if (i == "activity_begin_date") {
                  obj[i] = setStr(obj[i])
              }
              if (i == 'coupon_value') {
                  obj[i] = parseFloat(obj[i])
              }
              if (i == 'consume_amount') {
                  obj[i] = parseFloat(obj[i])
              }
          })
          return obj
      }
      if (typeAry) {
          let newData = obj.map((i) => {
              Object.keys(i).map((key) => {
                  if (key == ' ') {
                      i[key] = setStr(i[key])
                  }
                  if (key == 'coupon_value') {
                      i[key] = parseFloat(i[key])
                  }
                  if (key == 'consume_amount') {
                      i[key] = parseFloat(i[key])
                  }
                  if (key == "activity_end_date") {
                      i[key] = setStr(i[key])
                  }
                  if (key == "activity_begin_date") {
                      i[key] = setStr(i[key])
                  }
                  if (key == 'begin_date') {
                      i[key] = setStr(i[key])
                  }
                  if (key == 'end_date') {
                      i[key] = setStr(i[key])
                  }
                  if (key == 'prepay_amount') {
                      i[key] = parseFloat(i[key])
                  }
                  if (key == 'sale_price') {
                      i[key] = parseFloat(i[key])
                  }
                  if (key == 'origin_price') {
                      i[key] = parseFloat(i[key])
                  }
              })
              return i
          })
          return newData
      }

      function setStr(str) {
          let d = str.split(' ')[0].split(/[-.]/).slice(1)
          return d.join('.')
      }
  }
}

export { util }